from rest_framework.views import APIView
from apps.inform.models import Inform,InformRead
from django.db.models import Prefetch,Q
from apps.inform.serializers import InformSerialize
from rest_framework.response import Response
from apps.absent.models import Absent
from apps.absent.serializers import AbsentSerializer
from apps.oaauth.models import OADepartment
from django.db.models import Count
from django.views.decorators.cache import cache_page
from django.utils.decorators import method_decorator

# 对于函数视图 如果想缓存
# 设置缓存为15分钟
# @cache_page(60*15)
# def cache_demo_view(request):
    # pass

#
class LatestInformView(APIView):
    """
    返回最新10条数据
    """
    # 使用redis缓存首页 接口数据  缓存时间为15分钟
    # @method_decorator(cache_page(60*1))
    def get(self,request):
        print('home inform')
        # 一般人只能看到公共的通知 或者是自己部门的通知 董事会的人可以看到所有通知
        user = request.user
        if user.department.name != '董事会':
            informs = Inform.objects.prefetch_related(Prefetch("reads", queryset=InformRead.objects.filter(user_id=user.uid)),'departments').filter(Q(public=True) | Q(departments=user.department_id))[:10]
        else:
            # 董事会
            informs = Inform.objects.prefetch_related('reads', 'departments')[:10]
        # queryset = Inform.objects.prefetch_related('reads','departments')[:10]
        serialize = InformSerialize(informs,many=True)
        return Response(serialize.data)

class LatestAbsentView(APIView):
    # @method_decorator(cache_page(60 * 15))
    def get(self,request):
        # 董事会的人 可以看到所有人的考勤信息 非董事会的人只能看到自己部门的考勤信息
        user = request.user
        queryset = Absent.objects
        if user.department.name != '董事会':
            queryset = queryset.filter(requester__department_id=user.department.id)
        else:
            queryset = queryset.all()
        queryset = queryset[:10]
        serialize = AbsentSerializer(queryset,many=True)
        return Response(serialize.data)

class LatestDepartStuffCountView(APIView):
    # @method_decorator(cache_page(60 * 15))
    def get(self,request):
        # 不仅要查找部门信息 还要部门总数(聚合函数的字段)
        # values 指定只需要部分字段
        # rows为queryset对象
        rows = OADepartment.objects.annotate(staff_count=Count('staffs')).values('name','staff_count')
        # print(rows)
        # print(OADepartment.objects.annotate(staff_count=Count('staffs')).query)
        return Response(rows)

# apps/home/views.py
class HealthCheckView(APIView):
    def get(self, request):
        return Response({"code": 200})